<template>
  <div id="homeView">
    <a-row :gutter="[24, 24]">
      <!-- 用户信息卡片 -->
      <a-col :span="24" v-if="isLogin">
        <a-card class="user-card">
          <a-space align="center">
            <a-avatar :size="64"
              >{{ loginUser.userName?.slice(0, 2) }}
            </a-avatar>
            <div>
              <h3>{{ loginUser.userName }}</h3>
              <p>欢迎回来！</p>
            </div>
          </a-space>
        </a-card>
      </a-col>

      <!-- 未登录提示 -->
      <a-col :span="24" v-else>
        <a-card class="login-prompt">
          <a-space direction="vertical" align="center" fill>
            <h3>欢迎来到李 OJ</h3>
            <p>登录后可以查看其他人的提交记录和做题进度</p>
            <a-button type="primary" @click="toLogin">立即登录</a-button>
          </a-space>
        </a-card>
      </a-col>

      <!-- 最近提交记录 -->
      <a-col :span="24" v-if="isLogin">
        <a-card title="最近提交记录" class="submission-card">
          <a-table
            :columns="submissionColumns"
            :data="submissionData"
            :pagination="{
              showTotal: true,
              pageSize: submissionParams.pageSize,
              current: submissionParams.current,
              total: submissionTotal,
            }"
            @page-change="onSubmissionPageChange"
            :loading="submissionLoading"
          >
            <template #userName="{ record }">
              {{ record.userName }}
            </template>
            <template #judgeMessage="{ record }">
              <a-tag
                :color="
                  record.judgeInfo?.message === 'Accepted' ? 'green' : 'red'
                "
              >
                {{ record.judgeInfo?.message || "Wrong" }}
              </a-tag>
            </template>
            <template #judgeTime="{ record }">
              {{ record.judgeInfo?.time ?? 0 }} ms
            </template>
            <template #createTime="{ record }">
              {{ moment(record.createTime).format("YYYY-MM-DD HH:mm") }}
            </template>
            <template #action="{ record }">
              <a-button type="text" @click="toQuestion(record.questionId)">
                查看题目
              </a-button>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <!-- 热门题目 -->
      <a-col :span="24">
        <a-card title="热门题目" class="question-card">
          <a-table
            :columns="questionColumns"
            :data="questionData"
            :pagination="false"
            :loading="questionLoading"
          >
            <template #tags="{ record }">
              <a-space wrap>
                <a-tag
                  v-for="(tag, index) of record.tags"
                  :key="index"
                  color="green"
                >
                  {{ tag }}
                </a-tag>
              </a-space>
            </template>
            <template #acceptedRate="{ record }">
              {{
                record.submitNum
                  ? `${Math.round(
                      (record.acceptedNum / record.submitNum) * 100
                    )}% (${record.acceptedNum}/${record.submitNum})`
                  : `0% (0/0)`
              }}
            </template>
            <template #action="{ record }">
              <a-button type="primary" @click="toQuestionPage(record)">
                开始做题
              </a-button>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import moment from "moment";
import {
  QuestionControllerService,
  QuestionSubmitQueryRequest,
} from "../../generated/question";
import message from "@arco-design/web-vue/es/message";

const router = useRouter();
const store = useStore();

// 计算属性判断是否登录
const isLogin = computed(() => {
  return store.state.user.loginUser?.userRole !== "notLogin";
});

// 获取登录用户信息
const loginUser = computed(() => {
  return store.state.user.loginUser || { userName: "" };
});

// 跳转登录页
const toLogin = () => {
  router.push("/user/login");
};

// 提交记录相关
const submissionData = ref([]);
const submissionTotal = ref(0);
const submissionLoading = ref(false);
const submissionParams = ref<QuestionSubmitQueryRequest>({
  pageSize: 5,
  current: 1,
  sortField: "createTime",
  sortOrder: "descend",
});

const submissionColumns = [
  {
    title: "题号",
    dataIndex: "questionId",
  },
  {
    title: "编程语言",
    dataIndex: "language",
  },
  {
    title: "状态",
    slotName: "judgeMessage",
  },
  {
    title: "执行时间",
    slotName: "judgeTime",
  },
  {
    title: "提交者",
    slotName: "userName",
  },
  {
    title: "提交时间",
    slotName: "createTime",
  },
  {
    title: "操作",
    slotName: "action",
  },
];

const loadSubmissionData = async () => {
  if (!isLogin.value) return;

  submissionLoading.value = true;
  try {
    const res =
      await QuestionControllerService.listQuestionSubmitByPageUsingPost(
        submissionParams.value
      );
    if (res.code === 0) {
      submissionData.value = res.data.records;
      submissionTotal.value = res.data.total;
    } else {
      message.error("加载提交记录失败，" + res.message);
    }
  } finally {
    submissionLoading.value = false;
  }
};

const onSubmissionPageChange = (page: number) => {
  submissionParams.value = {
    ...submissionParams.value,
    current: page,
  };
};

// 热门题目相关
const questionData = ref([]);
const questionLoading = ref(false);

const questionColumns = [
  {
    title: "题号",
    dataIndex: "id",
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "标签",
    slotName: "tags",
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
  },
  {
    title: "操作",
    slotName: "action",
  },
];

const loadQuestionData = async () => {
  questionLoading.value = true;
  try {
    const res = await QuestionControllerService.listQuestionVoByPageUsingPost({
      pageSize: 5,
      current: 1,
      sortField: "submitNum",
      sortOrder: "descend",
    });
    if (res.code === 0) {
      questionData.value = res.data.records;
    } else {
      message.error("加载热门题目失败，" + res.message);
    }
  } finally {
    questionLoading.value = false;
  }
};

// 跳转到题目页面
const toQuestionPage = (question: any) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

// 跳转到题目页面（通过题号）
const toQuestion = (questionId: any) => {
  router.push({
    path: `/view/question/${questionId}`,
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadSubmissionData();
  loadQuestionData();
});

// 监听登录状态变化
watchEffect(() => {
  if (isLogin.value) {
    loadSubmissionData();
  }
});
</script>

<style scoped>
#homeView {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.user-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
}

.login-prompt {
  text-align: center;
  background: linear-gradient(135deg, #e0f7fa 0%, #b2ebf2 100%);
  border-radius: 8px;
}

.submission-card,
.question-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.arco-card-header) {
  border-bottom: none;
  padding-bottom: 0;
}

:deep(.arco-table) {
  border-radius: 8px;
}
</style>
